package com.bing.concurrent.cyclicbarrier;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

	// 徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan
	private static int[] timeWalk = { 5, 8, 15, 15, 10 };
	// 自驾游
	private static int[] timeSelf = { 1, 3, 4, 4, 5 };
	// 旅游大巴
	private static int[] timeBus = { 2, 4, 6, 6, 7 };

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//三个旅行团
		CyclicBarrier barrier=new CyclicBarrier(3);
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		executorService.submit(new Tour(barrier,"WlakTour",timeWalk));
		executorService.submit(new Tour(barrier,"SlefTour",timeSelf));
		executorService.submit(new Tour(barrier,"BusTour",timeBus));
		executorService.shutdown();
	}
	
	private static String getNowTime(){
		SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");
		return  dataFormat.format(new Date())+":";
	}
	
	static class Tour implements Runnable{
        private int[] times;
        private CyclicBarrier barrier;
        private String tourName;
        public Tour(CyclicBarrier barrier,String tourName,int[] times){
        	this.times=times;
        	this.tourName=tourName;
        	this.barrier=barrier;
        }
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(times[0] * 1000);
		         System.out.println(getNowTime() + tourName + " Reached Shenzhen");
		         barrier.await();
		         Thread.sleep(times[1] * 1000);
		         System.out.println(getNowTime() + tourName + " Reached Guangzhou");
		         barrier.await();
		         Thread.sleep(times[2] * 1000);
		         System.out.println(getNowTime() + tourName + " Reached Shaoguan");
		         barrier.await();
		         Thread.sleep(times[3] * 1000);
		         System.out.println(getNowTime() + tourName + " Reached Changsha");
		         barrier.await();
		         Thread.sleep(times[4] * 1000);
		         System.out.println(getNowTime() + tourName + " Reached Wuhan");
		         barrier.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}
